package com.android.lovely.room.chat.database

import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import com.android.lovely.user.UserManager
import com.kotlin.extensions.appContext
import java.io.File
import java.util.concurrent.ConcurrentHashMap

@Database(entities = [CacheMessage::class, ChatDataBean::class], version = 11)
abstract class ChatDatabase : RoomDatabase() {

    companion object {
        private val databaseDir = appContext.getDatabasePath("message").absolutePath
        private const val DATABASE_NAME = "LovelyChat.db"
        private val sManagers = ConcurrentHashMap<String, ChatDatabase>()

        fun getInstance(userId: String = UserManager.userInfo?.id.toString()): ChatDatabase =
            sManagers[userId] ?: run {
                val subDir = "$databaseDir/${userId}/"
                val databaseFile = File(subDir)
                if (!databaseFile.exists()) {
                    databaseFile.mkdirs()
                }
                buildDatabase(
                    appContext, "$subDir$DATABASE_NAME"
                ).also {
                    sManagers[userId] = it
                }
            }

        private fun buildDatabase(appContext: Context, dbName: String): ChatDatabase {
            return Room.databaseBuilder(appContext, ChatDatabase::class.java, dbName)
                .allowMainThreadQueries().fallbackToDestructiveMigration().build()
        }
    }

    abstract fun getChatDao(): ChatInfoDao

    abstract fun getModeDao(): ChatModelDao
}